<template>
  <div class="message-page-container">
    <el-card class="message-card">
      <template #header>
        <div class="card-header">
          <div class="title-wrapper">
            <i class="el-icon-bell title-icon"></i>
            <span class="title-text">系统消息</span>
          </div>
          <div class="header-actions">
            <span class="message-count">共 {{ total }} 条消息</span>
            <el-button
                v-if="total > 0"
                type="text"
                size="small"
                class="read-all-btn"
                @click="handleReadAll"
            >
              全部标为已读
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-wrapper" v-loading="loading" element-loading-text="加载中...">
        <el-table
            :data="auditMessagesWithStoreInfo"
            border
            fit
            highlight-current-row
            style="width: 100%"
        >
          <el-table-column
              label="店铺名"
              align="center"
              min-width="150px"
          >
            <template #default="scope">
              <div class="store-name">
                <i class="el-icon-shop store-icon"></i>
                <span>{{ scope.row.stores?.[0]?.name || '无店铺信息' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="消息内容"
              align="left"
              min-width="400px"
          >
            <template #default="scope">
              <el-tooltip content="点击查看详情" effect="light">
                <div
                    class="message-content"
                    :class="{ 'is-unread': !scope.row.read }"
                    @click="viewWhole(scope.row)"
                >
                  {{ scope.row.message.length > 50 ? scope.row.message.substring(0, 50) + '...' : scope.row.message }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column
              label="操作"
              align="center"
              min-width="180px"
          >
            <template #default="scope">
              <el-button
                  type="text"
                  size="small"
                  @click="viewWhole(scope.row)"
                  class="view-btn"
              >
                <i class="el-icon-view"></i> 查看详情
              </el-button>
              <el-button
                  type="text"
                  size="small"
                  @click="removeMessage(scope.row)"
                  class="delete-btn"
              >
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
<!--        <el-empty-->
<!--            v-if="auditMessagesWithStoreInfo && auditMessagesWithStoreInfo.length === 0"-->
<!--            image="empty"-->
<!--            description="暂无系统消息"-->
<!--        >-->
<!--          <template #image-slot>-->
<!--            <i class="el-icon-inbox empty-icon"></i>-->
<!--          </template>-->
<!--        </el-empty>-->
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pageNo"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="pageSizeChange"
            @current-change="pageNoChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getCurMerchant } from "@/api/merchant";
import {
  deleteAuditMessageById,
  listPagingAuditMessagesByMerchantIdWithStoreInfo
} from "@/api/audit-message";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";

// 状态管理
const auditMessagesWithStoreInfo = ref([]);
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const curMerchant = ref({});

// 获取商家信息并加载消息
const getCurMerchantInfo = async () => {
  try {
    loading.value = true;
    const res = await getCurMerchant();

    if (res.data) {
      curMerchant.value = res.data;
      await getAuditMessages();
    } else {
      ElMessageBox.alert('请先登录商家账号', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        router.push({ path: '/merchantLoginPage' });
      });
    }
  } catch (error) {
    ElMessage.error("获取商家信息失败，请稍后重试");
    console.error("获取商家信息失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取消息列表
const getAuditMessages = async () => {
  try {
    loading.value = true;
    const query = {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      merchantId: curMerchant.value.id,
    };

    const res = await listPagingAuditMessagesByMerchantIdWithStoreInfo(query);
    if (res.data) {
      auditMessagesWithStoreInfo.value = res.data.records || [];
      total.value = res.data.total || 0;
    } else {
      auditMessagesWithStoreInfo.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error("获取消息列表失败，请稍后重试");
    console.error("获取消息列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 分页事件处理
const pageNoChange = (value) => {
  pageNo.value = value;
  getAuditMessages();
};

const pageSizeChange = (value) => {
  pageSize.value = value;
  pageNo.value = 1; // 重置页码
  getAuditMessages();
};

// 查看详情
const viewWhole = (row) => {
  ElMessageBox.alert(row.message, '消息详情', {
    confirmButtonText: '我知道了',
    type: 'info',
    center: true,
    customClass: 'message-detail-box',
    callback: () => {
      // 标记为已读（如果需要）
      if (!row.read) {
        // 这里可以添加已读标记的API调用
        // 模拟已读状态更新
        row.read = true;
      }
    }
  });
};

// 删除消息
const removeMessage = (row) => {
  ElMessageBox.confirm(
      '确定要删除此消息吗？删除后将无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        showClose: false,
        closeOnClickModal: false
      }
  ).then(async () => {
    try {
      loading.value = true;
      const res = await deleteAuditMessageById(row.id);

      if (res.data) {
        ElMessage.success("消息已成功删除");
        getAuditMessages(); // 刷新列表
      } else {
        ElMessage.error("删除失败，请稍后重试");
      }
    } catch (error) {
      ElMessage.error("删除失败，请稍后重试");
      console.error("删除消息失败:", error);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 全部标为已读
const handleReadAll = () => {
  // 实际项目中这里需要调用标为已读的API
  ElMessageBox.confirm(
      '确定要将所有消息标记为已读吗？',
      '操作确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(() => {
    auditMessagesWithStoreInfo.value.forEach(item => {
      item.read = true;
    });
    ElMessage.success("已全部标记为已读");
  });
};

// 生命周期钩子
onMounted(() => {
  getCurMerchantInfo();
});
</script>

<style scoped lang="scss">
$primary-color: #409EFF;
$success-color: #67C23A;
$warning-color: #E6A23C;
$danger-color: #F56C6C;
$info-color: #909399;
$light-bg: #F5F7FA;
$card-radius: 12px;
$transition: all 0.3s ease;

.message-page-container {
  padding: 20px;
  min-height: calc(100vh - 64px); // 减去顶部导航高度
  background-color: #f9fafb;
}

.message-card {
  border-radius: $card-radius;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: none;
  transition: $transition;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  }

  // 卡片头部
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #f0f2f5;

    .title-wrapper {
      display: flex;
      align-items: center;

      .title-icon {
        color: $primary-color;
        font-size: 20px;
        margin-right: 8px;
        transition: $transition;

        &:hover {
          transform: rotate(15deg);
        }
      }

      .title-text {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 15px;

      .message-count {
        font-size: 14px;
        color: #606266;
        padding: 3px 0;
      }

      .read-all-btn {
        color: $primary-color;
        transition: $transition;

        &:hover {
          color: #66b1ff;
          background-color: rgba(64, 158, 255, 0.1);
        }
      }
    }
  }

  // 表格区域
  .table-wrapper {
    padding: 20px;
    background-color: #fff;

    // 表格样式
    .el-table {
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #f0f2f5;

      // 表头样式
      .el-table__header th {
        background-color: #f9fafb;
        color: #606266;
        font-weight: 500;
        border-bottom: 1px solid #f0f2f5;
        height: 48px;
      }

      // 表格行样式
      .el-table__row {
        transition: $transition;
        height: 60px;

        &:hover {
          background-color: #f5f7fa !important;
        }

        &.current-row {
          background-color: #e6f7ff !important;
        }
      }

      // 单元格样式
      .el-table__cell {
        padding: 10px 15px;
        border-bottom: 1px solid #f5f7fa;

        &.is-center {
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    // 店铺名称样式
    .store-name {
      display: flex;
      align-items: center;
      padding: 5px 10px;
      border-radius: 4px;
      transition: $transition;

      &:hover {
        background-color: rgba(64, 158, 255, 0.05);
      }

      .store-icon {
        color: $primary-color;
        margin-right: 8px;
        font-size: 16px;
      }
    }

    // 消息内容样式
    .message-content {
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 6px;
      transition: $transition;
      line-height: 1.6;
      max-width: 100%;

      &:hover {
        background-color: #f5f7fa;
        transform: translateX(3px);
      }

      &.is-unread {
        font-weight: 500;
        background-color: rgba(250, 248, 230, 0.5);
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 3px;
          height: 20px;
          border-radius: 3px;
          background-color: $warning-color;
        }
      }
    }

    // 操作按钮样式
    .view-btn {
      color: $primary-color;
      margin-right: 10px;
      transition: $transition;

      &:hover {
        color: #66b1ff;
        background-color: rgba(64, 158, 255, 0.1);
      }
    }

    .delete-btn {
      color: $danger-color;
      transition: $transition;

      &:hover {
        color: #f78989;
        background-color: rgba(245, 108, 108, 0.1);
      }
    }

    // 空状态样式
    .el-empty {
      padding: 80px 0;
      text-align: center;

      .empty-icon {
        font-size: 70px;
        color: #c0c4cc;
        margin-bottom: 20px;
        transition: $transition;

        &:hover {
          color: $primary-color;
          transform: scale(1.1) rotate(5deg);
        }
      }

      .el-empty__description {
        color: #909399;
        font-size: 15px;
      }
    }
  }

  // 分页区域样式
  .pagination-wrapper {
    padding: 15px 20px;
    background-color: #fcfcfc;
    border-top: 1px solid #f0f2f5;
    display: flex;
    justify-content: flex-end;
  }
}

// 消息详情弹窗样式
::v-deep .message-detail-box {
  width: 90%;
  max-width: 600px;

  .el-message-box__title {
    color: #303133;
    font-size: 18px;
    padding: 15px 20px;
    border-bottom: 1px solid #f0f2f5;
  }

  .el-message-box__content {
    padding: 25px 20px;
    font-size: 15px;
    line-height: 1.8;
    color: #606266;
    max-height: 400px;
    overflow-y: auto;
  }

  .el-message-box__btns {
    padding: 15px 20px;
    border-top: 1px solid #f0f2f5;
    display: flex;
    justify-content: center;

    .el-button--primary {
      background-color: $primary-color;
      border-color: $primary-color;

      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .message-page-container {
    padding: 10px;
  }

  .message-card {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;

      .header-actions {
        width: 100%;
        justify-content: space-between;
      }
    }

    .table-wrapper {
      padding: 10px 5px;

      .el-table {
        .el-table__cell {
          padding: 8px 5px;
          font-size: 13px;
        }

        // 消息内容适配
        .message-content {
          padding: 5px 8px;
          font-size: 13px;

          &.is-unread::before {
            width: 2px;
          }
        }
      }
    }

    .pagination-wrapper {
      padding: 10px;
      justify-content: center;

      .el-pagination {
        .el-pagination__total {
          display: none;
        }
      }
    }
  }

  ::v-deep .message-detail-box {
    .el-message-box__content {
      font-size: 14px;
      max-height: 300px;
    }
  }
}
</style>